package com.iot.service.mqtt.service.auth.http;

import com.google.gson.Gson;
import com.iot.service.mqtt.service.auth.AbstractTlAuthentication;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: hszhou
 * @Date: 2025/5/10 13:15
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class HttpTlAuthentication extends AbstractTlAuthentication {


    private final HttpClient client;

    private final Gson gson;

    @Override
    public boolean authenticate(String username, String password) {
        List<HttpEntityInfo> configs = getConfigs(username, password);
        // 2. 构造 JSON 请求体
        for (HttpEntityInfo config : configs) {

            // 根据方法类型分发请求
            int statusCode = switch (config.getMethod()) {
                case GET -> doGet(client, config.getParams(), config.getUrl());
                case POST -> {
                    String contentType = config.getHeaders().getOrDefault("Content-Type", "");
                    if (contentType.contains("application/json")) {
                        yield doPost(client, config.getParams(), config.getUrl());
                    } else if (contentType.contains("x-www-form-urlencoded")) {
                        yield doPostForm(client, config.getParams(), config.getUrl());
                    } else {
                        yield -1;
                    }
                }
                default -> -1;
            };
            if (statusCode == 200) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean enabled() {
        return true;
    }

    public List<HttpEntityInfo> getConfigs(String username, String password) {
        //认证的接口实例
        List<HttpEntityInfo> configs = new ArrayList<>();
        HashMap<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);


        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");


        HashMap<String, String> headers2 = new HashMap<>();
        headers2.put("Content-Type", "application/x-www-form-urlencoded");

        HttpEntityInfo config = new HttpEntityInfo();
        config.setUrl("http://127.0.0.1:8097/mqtt/login/test");
        config.setParams(params);
        config.setMethod(HttpMethod.POST);
        config.setHeaders(headers2);
        configs.add(config);

        HttpEntityInfo config2 = new HttpEntityInfo();
        config2.setUrl("http://127.0.0.1:8097/mqtt/login");
        config2.setParams(params);
        config2.setMethod(HttpMethod.POST);
        config2.setHeaders(headers);
        configs.add(config2);

        HttpEntityInfo config3 = new HttpEntityInfo();
        config3.setUrl("http://127.0.0.1:8097/mqtt/login/test");
        config3.setParams(params);
        config3.setMethod(HttpMethod.GET);
        config3.setHeaders(new HashMap<>(1));
        configs.add(config3);
        return configs;
    }

    private int doPost(HttpClient httpClient, HashMap<String, String> params, String url) {
        String jsonBody = gson.toJson(params);
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();

        try {
            HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
            return response.statusCode();
        } catch (Exception e) {
            log.error("HttpTlAuthentication:{}",e.getMessage());
        }
        return -1;
    }


    private int doPostForm(HttpClient httpClient, HashMap<String, String> params, String url) {

        String formData = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        // 创建请求
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString(formData))
                .build();
        try {
            HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
            return response.statusCode();
        } catch (Exception e) {
            log.error("HttpTlAuthentication:{}",e.getMessage());
        }
        return -1;
    }

    private int doGet(HttpClient httpClient, HashMap<String, String> params, String url) {


        String paramStr = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(url + "?" + paramStr))
                .GET()
                .build();
        try {
            HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
            return response.statusCode();
        } catch (Exception e) {
            log.error("HttpTlAuthentication:{}",e.getMessage());
        }
        return -1;
    }
}
